<?php

function addslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = addslashes_mssql($value);
        }
    } else {
        $str = str_replace("'", "''", $str);    
    }
    
    return $str;
}


function _convert($content) { 
    if(!mb_check_encoding($content, 'UTF-8') 
        OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) { 

        $content = mb_convert_encoding($content, 'UTF-8'); 

        if (mb_check_encoding($content, 'UTF-8')) { 
            // log('Converted to UTF-8'); 
        } else { 
            // log('Could not converted to UTF-8'); 
        } 
    } 
    return $content; 
} 

function firstOfPrevMonth() {
return date("Y.m.d", strtotime(date('n', mktime(0,0,0,(date('m')-1),28,date('Y'))).'/01/'.date('Y',mktime(0,0,0,(date('m')-1),28,date('Y'))).' 00:00:00'));
}

function lastOfPrevMonth() {
return date("Y.m.d", strtotime('-1 second',strtotime('+1 month',strtotime(date('n', mktime(0,0,0,(date('m')-1),28,date('Y'))).'/01/'.date('Y',mktime(0,0,0,(date('m')-1),28,date('Y'))).' 00:00:00'))));
}


function firstOfMonth() {
return date("Y.m.d", strtotime(date('m').'/01/'.date('Y').' 00:00:00'));
}

function lastOfMonth() {
return date("Y.m.d", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00'))));
}

function adddays($data,$dienos) {
list($year,$month,$day  ) = explode('.', $data);
return date("Y.m.d", strtotime('+' . $dienos .' day',  strtotime($month."/".$day."/".$year)));
}

/* 
## converts a given date format to another date format returns date if the checked date given is valid; otherwise returns NULL
## $s_date the date in e.g. dd/mm/yyyy
## $s_from, $s_to date formats from to i.e. convertdate('13/04/2009','eng','iso','-'); output: 2009-04-13
## date formats available
## 'eng' = dd/mm/yyyy
## 'usa' = mm/dd/yyyy
## 'iso' = yyyy/mm/dd
## $s_return_delimiter returned delimiter e.g. '-' would return dd-mm-yyyy 
*/
function convertdate($s_date,$s_from,$s_to,$s_return_delimiter) {

    $s_return_date = '';
    $s_from = strtolower($s_from);
    $s_to = strtolower($s_to);
    $s_date = str_replace(array('\'', '-', '.', ',', ' '), '/', $s_date);
    $a_date = explode('/', $s_date); 
    
	if (count($a_date)==3) {
    switch($s_from) {
        case 'eng': # dd/mm/yyyy
            $day = $a_date[0];
            $month = $a_date[1];
            $year = $a_date[2]; 
        break;
        case 'usa':  # mm/dd/yyyy
            $month = $a_date[0];
            $day = $a_date[1];
            $year = $a_date[2]; 
        break;
        case 'iso': # yyyy/mm/dd
            $year = $a_date[0]; 
            $month = $a_date[1];
            $day = $a_date[2];
        break;
        default: # error message
            user_error('function convertdate(string $s_date, string $s_from, string $s_to, string $s_return_delimiter) $s_from not a valid type of \'eng\', \'usa\' or \'iso\'');
            return NULL;
    }
	} else {
		return NULL;
	}
    # substitution fixes of valid alternative human input e.g. 1/12/08
    if (strlen($day)==1) { $day='0'.$day; } # day -trailing zero missing
    if (strlen($month)==1) { $month='0'.$month; } # month -trailing zero missing
    if (strlen($year)==3) { $year=substr(date('Y'),0,strlen(date('Y'))-3).$year; } # year -millennium missing
    if (strlen($year)==2) { $year=substr(date('Y'),0,strlen(date('Y'))-2).$year; } # year -century missing
    if (strlen($year)==1) { $year=substr(date('Y'),0,strlen(date('Y'))-1).$year; } # year -decade missing

    switch($s_to) {
        case 'eng': # dd/mm/yyyy
            $s_return_date = $day.$s_return_delimiter.$month.$s_return_delimiter.$year;
        break;
        case 'usa':  # mm/dd/yyyy
            $s_return_date = $month.$s_return_delimiter.$day.$s_return_delimiter.$year;
        break;
        case "iso": # yyyy/mm/dd
            $s_return_date = $year.$s_return_delimiter.$month.$s_return_delimiter.$day;
        break;
        default: # error message
            user_error('function convertdate(string $s_date, string $s_from, string $s_to, string $s_return_delimiter) $s_to not a valid type of \'eng\', \'usa\' or \'iso\'');
            return NULL;
    }

    # if it's an invalid calendar date e.g. 40/02/2009 or rt/we/garbage
    if (!is_numeric($month) || !is_numeric($day) || !is_numeric($year)) { 
        return NULL;
    } elseif (!checkdate($month, $day, $year)) {
        return NULL;
    }

    return $s_return_date;
} 


function toLit($NumberArg,$curr) {

if ($NumberArg < 1) {
	$ct = round(fmod(($NumberArg *100) , 100));
	if ($curr == "LTL")
		$strRez = "NULIS LITŲ " . " " . $ct ." ct";
	else
		$strRez = "NULIS EURŲ " . " " . $ct ." ct";
	return $strRez;
}

$strMillions = floor($NumberArg/1000000);
$m2 = "";
$m1 = "";
If ($strMillions > 0) {
	$m1 = TrysSkaitmenys($strMillions);
	$v = $strMillions % 100;
	$d = $strMillions % 10;
	if ($v >=10 && $v <20) {
		$m2 = "MILIJONŲ ";
	} else {
		switch ($d) {
			case 0:
				$m2 = "MILIJONŲ ";
				break;
			case 1:
				$m2 = "MILIJONAS ";
				break;
			default:
				$m2 = "MILIJONAI ";
		}
	}
}


$strThousands = floor(($NumberArg % 1000000)/1000);
$t2 = "";
$t1 = "";
If ($strThousands > 0) {
	$t1 = TrysSkaitmenys($strThousands);
	$v = $strThousands % 100;
	$d = $strThousands % 10;
	if ($v >=10 && $v <20) {
		$t2 = "TŪKSTANČIŲ ";
	} else {
		switch ($d) {
			case 0:
				$t2 = "TŪKSTANČIŲ ";
				break;
			case 1:
				$t2 = "TŪKSTANTIS ";
				break;
			default:
				$t2 = "TŪKSTANČIAI ";
		}
	}
}

$strHundreds = $NumberArg % 1000;

//echo $strHundreds;

$r1 = TrysSkaitmenys($strHundreds);
	$v = $strHundreds % 100;
	$d = $strHundreds % 10;
	if ($curr == "LTL")
		$r2 = "Lt ";
	else
		$r2 = "Eur ";

$ct = round(fmod(($NumberArg *100) , 100));

return $m1 . $m2 . $t1 . $t2 . $r1 . $r2 . " " . $ct ." ct";

}


function TrysSkaitmenys($strNum3) {


$s1 = floor($strNum3/100);
$d1 = floor(($strNum3 % 100)/10);
$d2 = $strNum3 % 100;
$v1 = $strNum3 % 10;

$s3 = $d3 = $v3 = "";

switch ($s1) {
Case 1:
	$s3 = "VIENAS ŠIMTAS "; break;
Case 2:
	$s3 = "DU ŠIMTAI "; break;
Case 3:
	$s3 = "TRYS ŠIMTAI "; break;
Case 4:
	$s3 = "KETURI ŠIMTAI "; break;
Case 5:
	$s3 = "PENKI ŠIMTAI "; break;
Case 6:
	$s3 = "ŠEŠI ŠIMTAI "; break;
Case 7:
	$s3 = "SEPTYNI ŠIMTAI "; break;
Case 8:
	$s3 = "AŠTUONI ŠIMTAI "; break;
Case 9:
	$s3 = "DEVYNI ŠIMTAI "; break;
}


switch ($d1) {
Case 1:
	switch ($d2) {
	Case 10:
	$d3 = "DEŠIMT "; break;
	Case 11:
	$d3 = "VIENUOLIKA "; break;
	Case 12:
	$d3 = "DVYLIKA "; break;
	Case 13:
	$d3 = "TRYLIKA "; break;
	Case 14:
	$d3 = "KETURIOLIKA "; break;
	Case 15:
	$d3 = "PENKIOLIKA "; break;
	Case 16:
	$d3 = "ŠEŠIOLIKA "; break;
	Case 17:
	$d3 = "SEPTYNIOLIKA "; break;
	Case 18:
	$d3 = "AŠTUONIOLIKA "; break;
	Case 19:
	$d3 = "DEVYNIOLIKA "; break;
	}
	break;
Case 2:
	$d3 = "DVIDEŠIMT "; break;
Case 3:
	$d3 = "TRISDEŠIMT "; break;
Case 4:
	$d3 = "KETURIASDEŠIMT "; break;
Case 5:
	$d3 = "PENKIASDEŠIMT "; break;
Case 6:
	$d3 = "ŠEŠIASDEŠIMT "; break;
Case 7:
	$d3 = "SEPTYNIASDEŠIMT "; break;
Case 8:
	$d3 = "AŠTUONIASDEŠIMT "; break;
Case 9:
	$d3 = "DEVYNIASDEŠIMT "; break;
}

If ($d1 != 1) {
	switch ($v1) {
	Case 1:
	$v3 = "VIENAS "; break;
	Case 2:
	$v3 = "DU "; break;
	Case 3:
	$v3 = "TRYS "; break;
	Case 4:
	$v3 = "KETURI "; break;
	Case 5:
	$v3 = "PENKI "; break;
	Case 6:
	$v3 = "ŠEŠI "; break;
	Case 7:
	$v3 = "SEPTYNI "; break;
	Case 8:
	$v3 = "AŠTUONI "; break;
	Case 9:
	$v3 = "DEVYNI "; break;
	}
}
return $s3 . $d3 . $v3;

}

function removeLtChars($input){
	$output = str_replace("ą","a",$input);
	$output = str_replace("č","c",$output);
	$output = str_replace("ę","e",$output);
	$output = str_replace("ė","e",$output);
	$output = str_replace("į","i",$output);
	$output = str_replace("š","s",$output);
	$output = str_replace("ų","u",$output);
	$output = str_replace("ū","u",$output);
	$output = str_replace("ž","z",$output);
	$output = str_replace("Ą","A",$output);
	$output = str_replace("Č","C",$output);
	$output = str_replace("Ę","E",$output);
	$output = str_replace("Ė","E",$output);
	$output = str_replace("Į","I",$output);
	$output = str_replace("Š","S",$output);
	$output = str_replace("Ų","U",$output);
	$output = str_replace("Ū","U",$output);
	$output = str_replace("Ž","Z",$output);
	RETURN $output;
}

function subtractDaysFromToday($number_of_days)
{
    $today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));

    $subtract = $today - (86400 * $number_of_days);

    //choice a date format here
    return date("Y.m.d", $subtract);
}

function logAction($veiksmas,$kodas){
	global $_SESSION;
	if (isset($_SESSION['user']) && isset($_SESSION['company'])) {
		logActionLong($_SESSION['user'],$_SESSION['company'],$veiksmas,$kodas);	
	}
}

function addDocComment($dok_nr,$comment) {
	global $comdel_query,$comins_query, $rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver;
	$db_rdata = new DB($rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver);
	if (!$db_rdata->isConnected()) {	
		return;
	}	

	$comdel_query = str_replace("<dok_nr>", addslashes_mssql($dok_nr), $comdel_query);
	$db_rdata->execute($comdel_query);
	$comins_query = str_replace("<dok_nr>", addslashes_mssql($dok_nr), $comins_query);
	$comins_query = str_replace("<comment>", addslashes_mssql(ltCharsToEntities(htmlspecialchars($comment))), $comins_query);
	$db_rdata->execute($comins_query);
}

function getDocComment($db_rdata,$dok_nr){
	global $comsel_query;
	if (!$db_rdata->isConnected()) {	
		return;
	}
	$sql = str_replace("<dok_nr>", addslashes_mssql($dok_nr), $comsel_query);
	$info = $db_rdata->returnInfo($sql);
	if(!empty($info)){
		return $info["tekstas"];
	} else {
		return;
	}
}

function ltCharsToEntities($input){
	$input = str_replace("ą","&#261;",$input);
	$input = str_replace("č","&#269;",$input);
	$input = str_replace("ę","&#281;",$input);
	$input = str_replace("ė","&#279;",$input);
	$input = str_replace("į","&#303;",$input);
	$input = str_replace("š","&#353;",$input);
	$input = str_replace("ų","&#371;",$input);
	$input = str_replace("ū","&#363;",$input);
	$input = str_replace("ž","&#382;",$input);
	$input = str_replace("Ą","&#260;",$input);
	$input = str_replace("Č","&#268;",$input);
	$input = str_replace("Ę","&#280;",$input);
	$input = str_replace("Ė","&#278;",$input);
	$input = str_replace("Į","&#302;",$input);
	$input = str_replace("Ų","&#370;",$input);
	$input = str_replace("Ū","&#362;",$input);
	$input = str_replace("Š","&#352;",$input);
	$input = str_replace("Ž","&#381;",$input);
	return $input;
}

function ltCharsFromEntities($input){
	$input = str_replace("&#261;","ą",$input);
	$input = str_replace("&#269;","č",$input);
	$input = str_replace("&#281;","ę",$input);
	$input = str_replace("&#279;","ė",$input);
	$input = str_replace("&#303;","į",$input);
	$input = str_replace("&#353;","š",$input);
	$input = str_replace("&#371;","ų",$input);
	$input = str_replace("&#363;","ū",$input);
	$input = str_replace("&#382;","ž",$input);
	$input = str_replace("&#260;","Ą",$input);
	$input = str_replace("&#268;","Č",$input);
	$input = str_replace("&#280;","Ę",$input);
	$input = str_replace("&#278;","Ė",$input);
	$input = str_replace("&#302;","Į",$input);
	$input = str_replace("&#370;","Ų",$input);
	$input = str_replace("&#362;","Ū",$input);
	$input = str_replace("&#352;","Š",$input);
	$input = str_replace("&#381;","Ž",$input);
	return $input;
}

function logActionLong($vart_id,$vart_pavad,$veiksmas,$kodas){
	global $action_log,$rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver,$_SERVER;
	
	
	if (isset($action_log) && $action_log == "1") {
	
		$db_rdata = new DB($rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver);
		if (!$db_rdata->isConnected()) {	
			return;
		}	
	
		$sql = "INSERT INTO History
			   (vart_id,vart_pavad,veiksmas,vart_ip,kodas)
		 VALUES
			   ('".addslashes_mssql(htmlentities($vart_id))."','" 
			   .addslashes_mssql(substr(@iconv( 'UTF-8','windows-1257', htmlspecialchars($vart_pavad)),0,39))."' ,'" 
			   .addslashes_mssql(substr(@iconv( 'UTF-8','windows-1257', htmlspecialchars($veiksmas)),0,39))."' ,'" 
			   .addslashes_mssql($_SERVER['REMOTE_ADDR'])."',".$kodas.")";
		$db_rdata->execute($sql);	   
	}	   
}

function print_file_contents($file) {
	if (file_exists($file)) {
		$fh = fopen($file, 'r');
		$theData = fread($fh, filesize($file));
		fclose($fh);
		echo $theData;
	} else {
		echo "Nerastas failas: " . $file;
	}
}

function getRobotukasInfo(){

	$color = "red";
	$laikas = "";
	$tekstas = "Robotukas neveikia" . ' <span style="color:'. $color . ';">&diams;</span>';
	if (file_exists('online.txt')) {
		$fhh = fopen('online.txt', 'r');
		$laikas = substr(fread($fhh, filesize('online.txt')),0,32);
		fclose($fhh);
		$laikas_last = strtotime(substr($laikas,0,21));
		$laikas_now = time();
		if (($laikas_last+(12 * 60 * 60)) > $laikas_now) {
			$color = "green";
			$tekstas = "Robotukas buvo paleistas: " . $laikas . ' <span style="color:'. $color . ';">&diams;</span>';
		} else if ((($laikas_last+(12 * 60 * 60)) <= $laikas_now) 
					&& (($laikas_last+(24 * 60 * 60)) > $laikas_now)) {
			$color = "yellow";
			$tekstas = "Robotukas buvo paleistas: " . $laikas . ' <span style="color:'. $color . ';">&diams;</span>';
		}
	}
	return $tekstas;
	//
}

function getVersionInfo(){

	if (file_exists('.svn/entries')) {
		
		//$cont = file_get_contents('.svn/entries'); 
		$cont = file_get_contents('versija.txt'); 
		//$pos = strpos ($cont,"dir"); 
		//$pos2 = strpos ($cont,"\n",$pos+3); 
		$ver = trim(substr($cont,0,5));
		//if (file_exists('gver.txt')) {	
		//	$modtime = filemtime('gver.txt');
		//	$skirtumas = time()-$modtime;
		//	if ($skirtumas > (60*60*24)) {
		//		$tikrinti = true;
		//	} else {
		//		$tikrinti = false;
		//	}
		//} else {
		//	$tikrinti = true;
		//}

		//if ($tikrinti) {
		//		// set url 
		//		$cont = file_get_contents("http://code.google.com/feeds/p/vsriv/svnchanges/basic?path=/branches/v3/"); 
		//		$pos = strpos ($cont,"?r="); 
		//		if ($pos) {
		//			$pos2 = strpos ($cont,"&amp;",$pos+4); 
		//			if ($pos2) {
		//				$gver = substr($cont,$pos+3,$pos2-$pos-3);
		//			} else {
		//				$gver = "";
		//			}
		//		} else {
		//			$gver = "";
		//		}
			//irasom i faila
		//	$myFile = "gver.txt";
		//	$fh = fopen($myFile, 'w');
		//	fwrite($fh, $gver);
		//	fclose($fh);		
		//} else {
		//	$gver = file_get_contents("gver.txt");
		//}
	} else {
		$ver = "";
		$gver = "";
	}
	//if (is_numeric($ver) && is_numeric($gver) && intval($ver) >= intval($gver)) {	
		return "Klientams2 versija: " . $ver;	
	//} else {	
	//	return "Idiegta versija: <span style='color:red;'>" . $ver . "</span>, <b>Naujausia versija: " . $gver . "</b>";	
	//}

}

function isMenuSelected($serv_script,$script) {
	$pos = strpos($serv_script, $script);
	if ($pos === false) {
		return "mitem2";
	} else {
		return "mselected";
	}
}

function printActiveDocumentsTable($imkodas){
global $ns_query3,$db_www,$ns_query2 ;

$ns_query2 = str_replace("<im_kodas>", $imkodas, $ns_query2);
$ns = $db_www->returnList($ns_query2);	
?>
<table cellspacing="0" cellpadding="5" align="left" class="innercont3">
<tr>
<td class="th3">Aktyvūs dokumentai</td>

<th>Data</th><th>Numeris</th><th>Apmokėti iki</th><th>Dienos</th><th>Suma</th><th>Neapmokėta suma</th><th>Avansinis likutis</th></tr>
<?php
foreach ($ns as $account) {
	//if ($account["i44_suma_DB"] != $account["i44_suma_CR"]) {
		
		$ns_q = str_replace("<im_kodas>", $imkodas, $ns_query3);
		$ns_q = str_replace("<dok_nr>", $account["i44_dok_nr"], $ns_q);
		$ns1 = $db_www->returnInfo($ns_q);	
		//echo $ns_q;
		if ($ns1["dienos"] >=0 ){
			$color = "green";
		} else {
			$color = "red";
		} 
		$likutis = $account["db"]-$account["cr"];
		echo "<tr><td>&nbsp;</td><td>".$ns1["I44_DATA_DOK"]."</td>";
		echo "<td>".$account["i44_dok_nr"]."</td>";
		echo "<td>";
		if ($likutis >= 0) {
			echo $ns1["I44_DATA_MOK"];
		}
		echo "</td>";
		echo "<td style='color:".$color.";'>";
		if ($likutis >= 0) {
			echo $ns1["dienos"];
		}
		echo "</td>";
		echo "<td>";
		if ($likutis >= 0) {
			echo $account["db"];
		}
		echo "</td>";
		echo "<td>";
		if ($likutis >= 0) {
			echo $likutis;
		}
		echo "</td>";
		echo "<td>";
		if ($likutis < 0) {
			echo ($likutis*(-1));
		}
		echo "</td></tr>";
		
		
	//}
}
?>
<tr><td>&nbsp;</td></tr>
</table>
<?php




}

if( !function_exists('date_parse_from_format') ){
    function date_parse_from_format($format, $date) {
        // reverse engineer date formats
        $keys = array(
            'Y' => array('year', '\d{4}'),              //Année sur 4 chiffres
            'y' => array('year', '\d{2}'),              //Année sur 2 chiffres
            'm' => array('month', '\d{2}'),             //Mois au format numérique, avec zéros initiaux
            'n' => array('month', '\d{1,2}'),           //Mois sans les zéros initiaux
            'M' => array('month', '[A-Z][a-z]{3}'),     //Mois, en trois lettres, en anglais
            'F' => array('month', '[A-Z][a-z]{2,8}'),   //Mois, textuel, version longue; en anglais, comme January ou December
            'd' => array('day', '\d{2}'),               //Jour du mois, sur deux chiffres (avec un zéro initial)
            'j' => array('day', '\d{1,2}'),             //Jour du mois sans les zéros initiaux
            'D' => array('day', '[A-Z][a-z]{2}'),       //Jour de la semaine, en trois lettres (et en anglais)
            'l' => array('day', '[A-Z][a-z]{6,9}'),     //Jour de la semaine, textuel, version longue, en anglais
            'u' => array('hour', '\d{1,6}'),            //Microsecondes
            'h' => array('hour', '\d{2}'),              //Heure, au format 12h, avec les zéros initiaux
            'H' => array('hour', '\d{2}'),              //Heure, au format 24h, avec les zéros initiaux
            'g' => array('hour', '\d{1,2}'),            //Heure, au format 12h, sans les zéros initiaux
            'G' => array('hour', '\d{1,2}'),            //Heure, au format 24h, sans les zéros initiaux
            'i' => array('minute', '\d{2}'),            //Minutes avec les zéros initiaux
            's' => array('second', '\d{2}')             //Secondes, avec zéros initiaux
        );

        // convert format string to regex
        $regex = '';
        $chars = str_split($format);
        foreach ( $chars AS $n => $char ) {
            $lastChar = isset($chars[$n-1]) ? $chars[$n-1] : '';
            $skipCurrent = '\\' == $lastChar;
            if ( !$skipCurrent && isset($keys[$char]) ) {
                $regex .= '(?P<'.$keys[$char][0].'>'.$keys[$char][1].')';
            }
            else if ( '\\' == $char ) {
                $regex .= $char;
            }
            else {
                $regex .= preg_quote($char);
            }
        }

        $dt = array();
        $dt['error_count'] = 0;
        // now try to match it
        if( preg_match('#^'.$regex.'$#', $date, $dt) ){
            foreach ( $dt AS $k => $v ){
                if ( is_int($k) ){
                    unset($dt[$k]);
                }
            }
            if( !checkdate($dt['month'], $dt['day'], $dt['year']) ){
                $dt['error_count'] = 1;
            }
        }
        else {
            $dt['error_count'] = 1;
        }
        $dt['errors'] = array();
        $dt['fraction'] = '';
        $dt['warning_count'] = 0;
        $dt['warnings'] = array();
        $dt['is_localtime'] = 0;
        $dt['zone_type'] = 0;
        $dt['zone'] = 0;
        $dt['is_dst'] = '';
        return $dt;
    }
}


function printUserEditMenu($page_ret,$code,$n60_kodas_sm,$n60_pareigos){
?>
<table id="newbut" cellspacing="0" cellpadding="5" class="params"><tbody><tr><td style="text-align:center;"><a id="blockButton" onclick="window.location='user.php?ret=<?php echo $page_ret;?>&code=<?php echo $code;?>';return false;" class="card3">Kliento duomenys</a></td></tr></tbody></table>
<br>
<table id="newbut" cellspacing="0" cellpadding="5" class="params"><tbody><tr><td style="text-align:center;"><a id="blockButton" onclick="window.location='adiscounts.php?code=<?php echo $code;?>';return false;" class="card3">Nuolaidų sistema</a></td></tr></tbody></table>
<br>
<table id="newbut" cellspacing="0" cellpadding="5" class="params"><tbody><tr><td style="text-align:center;"><a id="blockButton" onclick="window.location='apayments.php?code=<?php echo $code;?>';return false;" class="card3">Finansai</a></td></tr></tbody></table>
<br>
<table id="newbut" cellspacing="0" cellpadding="5" class="params"><tbody><tr><td style="text-align:center;"><a id="blockButton" onclick="window.open('<?php echo "nauja.php?id=".trim($n60_kodas_sm)."&p=".md5(trim($n60_pareigos))?>', '_blank', 'location=yes,height=570,width=920,scrollbars=yes,status=yes');" class="card3">Kliento sistema</a></td></tr></tbody></table>

<?php
}


function getNuolGrPav($gid){
	global $db_www;
	$test_q = "SELECT N19_KODAS_GS,N19_PAV FROM [n19_pgr] WHERE [N19_KODAS_GS] = '".addslashes_mssql($gid)."'";
		
	$im = $db_www->returnInfo($test_q);	
	if ($im == null) {
		return "";
	} else {
		return iconv('windows-1257','UTF-8', trim($im["N19_PAV"]));
	}	
	
}



function printReceivedPaymentsTable($imkodas){
global $mokejimai_query,$db_www;
		$mokejimai_query = str_replace("<im_kodas>", $imkodas, $mokejimai_query);
		$mokejimai = $db_www->returnList($mokejimai_query);
		
		
if (!empty($mokejimai)) {

$gautimokejimai = '<table class="innercont3" cellspacing="0" cellpadding="5"><tr><td class="th3">Gauti mokėjimai</td></tr><tr><td>';
$gautimokejimai .= '<table cellspacing="0" cellpadding="5" align="left" class="innercont3">';
$gautimokejimai .= '<tr>';


$gautimokejimai .='<th>Data</th><th>Numeris</th><th>Suma</th></tr>';
foreach ($mokejimai as $mokejimas) {
	$gautimokejimai .=  "<tr><td>".$mokejimas["i04_op_data"]."</td>";
	$gautimokejimai .=  "<td>".$mokejimas["i04_dok_nr"]."</td>";
	$gautimokejimai .=  "<td>".$mokejimas["i04_suma"]."</td></tr>";
}

$gautimokejimai .= '</td></tr>';
$gautimokejimai .= '</table></td></tr></table>';


} else {
	$gautimokejimai = "";
}
echo $gautimokejimai;

}

function printCardTurnover($card){
   global $db_rdata;
   
   
   $sql = "select sum(suma) as suma from kvitogalva where kortelesnr = '".addslashes_mssql($card)."' and data >= '".firstOfMonth()."'";
   $im = $db_rdata->returnInfo($sql);	
	if ($im == null) {
		return '';
	} else {
if (isset($im["suma"]) && $im["suma"]!=null) {
		return sprintf("%01.2f",$im["suma"]);
} else {
		return '';
}
	}

}
function getGroupName($grid){
   global $db_www;
   
   
   $sql = "select N19_PAV from n19_pgr where N19_KODAS_GS = '".addslashes_mssql($grid)."'";
   $im = $db_www->returnInfo($sql);	
	if ($im == null) {
		return '';
	} else {

		return $im["N19_PAV"];

	}

}

function validateDate($date, $format = 'Y-m-d H:i:s')
{
	$d = DateTime::createFromFormat($format, $date);
	return $d && $d->format($format) == $date;
}



function checkConnection(){
	global $db_www,$db_rdata;
	if (!$db_www->isConnected()) {	
		return new soap_fault('-1', '', 'Error rivile db not connected!','');
	}	
	if (!$db_rdata->isConnected()) {	
		return new soap_fault('-2', '', 'Error rdata db not connected!','');
	}	
	return "";
}

function checkUserRights($user_id,$pass){
	global $db_www,$u_query;
	$user_id = addslashes_mssql($user_id);
	$pass = addslashes_mssql($pass);
	$u_query = str_replace("<get_username>", $user_id, $u_query);
	$u_query = str_replace("<get_password>", $pass, $u_query);					
	$info = $db_www->returnInfo($u_query);									
	if (!empty($info)) {	
	   return $info["r05_kodas_rs"];
	}
	return "";
}

function convpsw($psw) {
	$result = "";
	$length = strlen($psw);
	
	for ($i=0; $i<10; $i++) {
		if ($i < $length) {
			$result .= str_pad(ord($psw[$i]),3,"0",STR_PAD_LEFT);
		} else {
			$result .= "032";
		}
	}

	return $result;
}



function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}
function endsWith($haystack, $needle) {
    // search forward starting from end minus needle length characters
    return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
}



?>